﻿using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace JiraRest
{
    public class WebClient
    {
        private readonly CookieContainer m_CookieContainer = new CookieContainer();

        public string Get(string url)
        {
            HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(url);
            webRequest.CookieContainer = m_CookieContainer;
            return new StreamReader(webRequest.GetResponse().GetResponseStream()).ReadToEnd();
        }

        public string Post(string url, string content)
        {
            return SendHttp(url, content, "POST");
        }

        public string Put(string url, string content)
        {
            return SendHttp(url, content, "PUT");
        }

        private string SendHttp(string url, string content, string method)
        {
            HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(url);
            webRequest.CookieContainer = m_CookieContainer;
            webRequest.Method = method;
            byte[] contentBytes = Encoding.UTF8.GetBytes(content);
            webRequest.ContentLength = contentBytes.Length;
            webRequest.ContentType = "application/json; charset=utf-8";

            using (Stream requestStream = webRequest.GetRequestStream())
            {
                requestStream.Write(contentBytes, 0, contentBytes.Length);
            }

            WebResponse webResponse = webRequest.GetResponse();
            Stream responseStream = webResponse.GetResponseStream();
            return new StreamReader(responseStream).ReadToEnd();
        }
    }
}
